<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
      th:replace="~{layout/base :: layout(~{::title}, ~{::section})}">
<head>
    <meta charset="UTF-8">
    <title th:text="${book.title + ' - 电子书下载平台'}">书籍标题 - 电子书下载平台</title>
</head>
<body>
    <section>
        <div class="container py-5">
            <!-- 书籍基本信息 -->
            <div class="row mb-4">
                <!-- 书籍封面 -->
                <div class="col-md-3 mb-4 mb-md-0">
                    <img th:src="${book.coverUrl != null ? book.coverUrl : '/img/default-cover.jpg'}" 
                         alt="书籍封面" class="img-fluid book-detail-cover shadow">
                    
                    <!-- 下载按钮区域 -->
                    <div class="card mt-3">
                        <div class="card-body">
                            <h5 class="card-title">可用格式</h5>
                            
                            <!-- 用户已登录 -->
                            <div sec:authorize="isAuthenticated()">
                                <div class="d-grid gap-2" th:if="${book.availableFormats != null && !book.availableFormats.isEmpty()}">
                                    <a th:each="format : ${book.availableFormats}" 
                                       th:href="@{'/api/book/download/' + ${book.bookId} + '?format=' + ${format}}"
                                       class="btn" th:classappend="${format == 'PDF' ? 'btn-danger' : (format == 'EPUB' ? 'btn-primary' : 'btn-success')}"
                                       th:text="${'下载 ' + format}">下载 PDF</a>
                                </div>
                                <!-- 格式转换请求 -->
                                <div class="mt-3" th:if="${!book.availableFormats.contains('EPUB') || !book.availableFormats.contains('MOBI') || !book.availableFormats.contains('PDF')}">
                                    <hr>
                                    <h6>请求格式转换:</h6>
                                    <form th:action="@{'/api/book/convert/' + ${book.bookId}}" method="post" class="d-flex">
                                        <select class="form-select me-2" name="targetFormat">
                                            <option value="EPUB" th:if="${!book.availableFormats.contains('EPUB')}">EPUB</option>
                                            <option value="MOBI" th:if="${!book.availableFormats.contains('MOBI')}">MOBI</option>
                                            <option value="PDF" th:if="${!book.availableFormats.contains('PDF')}">PDF</option>
                                        </select>
                                        <button type="submit" class="btn btn-outline-primary">转换</button>
                                    </form>
                                    <small class="text-muted mt-1">格式转换需要一些时间，完成后将通知您</small>
                                </div>
                            </div>
                            
                            <!-- 未登录用户 -->
                            <div sec:authorize="!isAuthenticated()">
                                <p class="text-center">请<a th:href="@{/login}">登录</a>后下载</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 在线阅读 -->
                    <div class="d-grid mt-3">
                        <a th:href="@{'/books/read/' + ${book.bookId}}" class="btn btn-outline-primary"
                           sec:authorize="isAuthenticated()">
                            <i class="fas fa-book-reader me-2"></i>在线阅读
                        </a>
                        <a th:href="@{/login}" class="btn btn-outline-primary"
                           sec:authorize="!isAuthenticated()">
                            <i class="fas fa-book-reader me-2"></i>登录后在线阅读
                        </a>
                    </div>
                </div>
                
                <!-- 书籍详细信息 -->
                <div class="col-md-9">
                    <div class="card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <h2 class="card-title mb-0" th:text="${book.title}">书籍标题</h2>
                                <div>
                                    <!-- 收藏按钮 -->
                                    <button class="btn btn-outline-danger btn-sm me-2" id="favoriteBtn" sec:authorize="isAuthenticated()"
                                            th:data-book-id="${book.bookId}" th:data-is-favorite="${book.inCollection}">
                                        <i class="far fa-heart" th:classappend="${book.inCollection ? 'fas' : 'far'}"></i>
                                        <span th:text="${book.inCollection ? '已收藏' : '收藏'}">收藏</span>
                                    </button>
                                    
                                    <!-- 添加到书单 -->
                                    <div class="dropdown d-inline-block" sec:authorize="isAuthenticated()">
                                        <button class="btn btn-outline-primary btn-sm dropdown-toggle" type="button" 
                                                id="addToListDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                            添加到书单
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="addToListDropdown">
                                            <li th:each="list : ${userBooklists}">
                                                <a class="dropdown-item add-to-list" href="#" 
                                                   th:data-list-id="${list.listId}" th:data-book-id="${book.bookId}"
                                                   th:text="${list.listName}">书单名称</a>
                                            </li>
                                            <li th:if="${userBooklists == null || userBooklists.isEmpty()}">
                                                <span class="dropdown-item text-muted">暂无书单</span>
                                            </li>
                                            <li><hr class="dropdown-divider"></li>
                                            <li>
                                                <a class="dropdown-item" th:href="@{/user/booklists/create}">
                                                    <i class="fas fa-plus me-2"></i>创建新书单
                                                </a>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 基本信息 -->
                            <div class="mb-4">
                                <div class="d-flex flex-wrap">
                                    <span class="badge bg-secondary me-2 mb-2">
                                        <i class="fas fa-user me-1"></i> 作者: <span th:text="${book.author}">作者名</span>
                                    </span>
                                    <span class="badge bg-secondary me-2 mb-2" th:if="${book.translator != null && !book.translator.isEmpty()}">
                                        <i class="fas fa-language me-1"></i> 译者: <span th:text="${book.translator}">译者名</span>
                                    </span>
                                    <span class="badge bg-secondary me-2 mb-2" th:if="${book.publisher != null && !book.publisher.isEmpty()}">
                                        <i class="fas fa-building me-1"></i> 出版社: <span th:text="${book.publisher}">出版社</span>
                                    </span>
                                    <span class="badge bg-secondary me-2 mb-2" th:if="${book.pubYear != null}">
                                        <i class="fas fa-calendar-alt me-1"></i> 出版年份: <span th:text="${book.pubYear}">2023</span>
                                    </span>
                                    <span class="badge bg-secondary me-2 mb-2" th:if="${book.language != null && !book.language.isEmpty()}">
                                        <i class="fas fa-globe me-1"></i> 语言: <span th:text="${book.language}">简体中文</span>
                                    </span>
                                    <span class="badge bg-secondary me-2 mb-2" th:if="${book.isbn10 != null && !book.isbn10.isEmpty()}">
                                        <i class="fas fa-barcode me-1"></i> ISBN-10: <span th:text="${book.isbn10}">0123456789</span>
                                    </span>
                                    <span class="badge bg-secondary me-2 mb-2" th:if="${book.isbn13 != null && !book.isbn13.isEmpty()}">
                                        <i class="fas fa-barcode me-1"></i> ISBN-13: <span th:text="${book.isbn13}">9780123456789</span>
                                    </span>
                                    <a th:href="@{'/books/category/' + ${book.categoryId}}" class="badge-category me-2 mb-2">
                                        <i class="fas fa-tag me-1"></i> <span th:text="${book.categoryName}">分类名</span>
                                    </a>
                                </div>
                                
                                <div class="mt-3">
                                    <div class="d-flex align-items-center">
                                        <div class="rating me-2">
                                            <i class="fas fa-star"></i>
                                            <span th:text="${book.rating}">4.5</span>
                                        </div>
                                        <span class="text-muted me-3">
                                            <i class="fas fa-download me-1"></i>
                                            <span th:text="${book.downloadCount + ' 次下载'}">1200 次下载</span>
                                        </span>
                                        <span class="text-muted">
                                            上传者: <a th:href="@{'/user/profile/' + ${book.uploaderId}}" 
                                                     th:text="${book.uploaderNickname}">用户昵称</a>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 书籍简介 -->
                            <div class="mb-4">
                                <h5>内容简介</h5>
                                <p th:text="${book.description}">这里是书籍简介内容，详细介绍这本书的主要内容和亮点...</p>
                            </div>
                            
                            <!-- 修改信息 -->
                            <div class="mt-4 text-end">
                                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#modifyInfoModal">
                                    <i class="fas fa-edit me-1"></i>提出信息更正
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 评论区 -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">读者评论</h5>
                </div>
                <div class="card-body">
                    <!-- 添加评论表单 -->
                    <div class="mb-4" sec:authorize="isAuthenticated()">
                        <form th:action="@{'/api/comment/book/' + ${book.bookId}}" method="post">
                            <div class="mb-3">
                                <textarea class="form-control" id="commentContent" name="content" rows="3" placeholder="分享您的阅读体验..." required></textarea>
                            </div>
                            <div class="text-end">
                                <button type="submit" class="btn btn-primary">发表评论</button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- 评论列表 -->
                    <div th:if="${comments != null && !comments.isEmpty()}">
                        <!-- 动态评论内容 -->
                        <div th:each="comment : ${comments}" class="comment-item mb-4">
                            <div class="d-flex">
                                <div class="flex-shrink-0">
                                    <img th:src="${comment.avatar != null ? comment.avatar : '/img/default-avatar.jpg'}" 
                                         class="rounded-circle" width="50" height="50" alt="用户头像">
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <div>
                                            <a th:href="@{'/user/profile/' + ${comment.userId}}" class="fw-bold" th:text="${comment.nickname}">用户昵称</a>
                                            <small class="text-muted ms-2" th:text="${#temporals.format(comment.createdAt, 'yyyy-MM-dd HH:mm')}">2023-01-15 12:30</small>
                                        </div>
                                        <button class="btn btn-sm text-muted like-button" th:data-comment-id="${comment.commentId}"
                                                th:classappend="${comment.userLiked ? 'liked' : ''}">
                                            <i class="far fa-heart" th:classappend="${comment.userLiked ? 'fas' : 'far'}"></i>
                                            <span class="like-count" th:text="${comment.likes}">12</span>
                                        </button>
                                    </div>
                                    <div class="comment-bubble mb-2" th:text="${comment.content}">评论内容</div>
                                    
                                    <!-- 回复链接 -->
                                    <div class="d-flex text-muted">
                                        <a href="#" class="reply-link" sec:authorize="isAuthenticated()"
                                           th:data-comment-id="${comment.commentId}"
                                           th:data-user-name="${comment.nickname}">
                                            <small><i class="fas fa-reply me-1"></i>回复</small>
                                        </a>
                                    </div>
                                    
                                    <!-- 回复表单 -->
                                    <div th:id="${'replyForm-' + comment.commentId}" class="reply-form mt-2" style="display: none;">
                                        <form th:action="@{'/api/comment/book/' + ${book.bookId}}" method="post">
                                            <input type="hidden" name="parentCommentId" th:value="${comment.commentId}">
                                            <div class="input-group">
                                                <input type="text" class="form-control form-control-sm" name="content"
                                                       th:placeholder="${'回复 @' + comment.nickname}" required>
                                                <button class="btn btn-outline-primary btn-sm" type="submit">发送</button>
                                            </div>
                                        </form>
                                    </div>
                                    
                                    <!-- 回复列表 -->
                                    <div class="replies mt-2" th:if="${comment.replies != null && !comment.replies.isEmpty()}">
                                        <div th:each="reply : ${comment.replies}" class="reply-item ms-4 mb-2">
                                            <div class="d-flex">
                                                <div class="flex-shrink-0">
                                                    <img th:src="${reply.avatar != null ? reply.avatar : '/img/default-avatar.jpg'}" 
                                                         class="rounded-circle" width="35" height="35" alt="用户头像">
                                                </div>
                                                <div class="flex-grow-1 ms-2">
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <div>
                                                            <a th:href="@{'/user/profile/' + ${reply.userId}}" class="fw-bold" th:text="${reply.nickname}">回复用户</a>
                                                            <small class="text-muted ms-2" th:text="${#temporals.format(reply.createdAt, 'yyyy-MM-dd HH:mm')}">2023-01-16 09:15</small>
                                                        </div>
                                                    </div>
                                                    <div class="comment-bubble" th:text="${reply.content}">回复内容</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 静态示例，当没有评论时显示 -->
                    <div th:if="${comments == null || comments.isEmpty()}" class="text-center py-4">
                        <i class="far fa-comment-dots fa-3x text-muted mb-3"></i>
                        <p>暂无评论，成为第一个发表评论的人吧！</p>
                    </div>
                    
                    <!-- 分页控件 -->
                    <nav aria-label="Comment pagination" th:if="${totalCommentPages > 1}">
                        <ul class="pagination justify-content-center">
                            <li class="page-item" th:classappend="${currentCommentPage == 1} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{'/books/' + ${book.bookId} + '?commentPage=1'}" aria-label="First">
                                    <span aria-hidden="true">&laquo;&laquo;</span>
                                </a>
                            </li>
                            <li class="page-item" th:classappend="${currentCommentPage == 1} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{'/books/' + ${book.bookId} + '?commentPage=' + ${currentCommentPage - 1}}" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <li class="page-item" th:each="i : ${#numbers.sequence(currentCommentPage > 2 ? currentCommentPage - 2 : 1, currentCommentPage + 2 < totalCommentPages ? currentCommentPage + 2 : totalCommentPages)}"
                                th:classappend="${i == currentCommentPage} ? 'active' : ''">
                                <a class="page-link" th:href="@{'/books/' + ${book.bookId} + '?commentPage=' + ${i}}" th:text="${i}">1</a>
                            </li>
                            <li class="page-item" th:classappend="${currentCommentPage == totalCommentPages} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{'/books/' + ${book.bookId} + '?commentPage=' + ${currentCommentPage + 1}}" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                            <li class="page-item" th:classappend="${currentCommentPage == totalCommentPages} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{'/books/' + ${book.bookId} + '?commentPage=' + ${totalCommentPages}}" aria-label="Last">
                                    <span aria-hidden="true">&raquo;&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
        
        <!-- 信息修改弹窗 -->
        <div class="modal fade" id="modifyInfoModal" tabindex="-1" aria-labelledby="modifyInfoModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modifyInfoModalLabel">提出信息更正</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form th:action="@{'/api/book/' + ${book.bookId} + '/modify'}" method="post">
                        <div class="modal-body">
                            <div class="alert alert-info">
                                <small>提交后管理员将审核您的修改建议，审核通过后将更新书籍信息。</small>
                            </div>
                            
                            <div class="mb-3">
                                <label for="modifyTitle" class="form-label">书名</label>
                                <input type="text" class="form-control" id="modifyTitle" name="title" 
                                       th:value="${book.title}">
                            </div>
                            
                            <div class="mb-3">
                                <label for="modifyAuthor" class="form-label">作者</label>
                                <input type="text" class="form-control" id="modifyAuthor" name="author"
                                       th:value="${book.author}">
                            </div>
                            
                            <div class="mb-3">
                                <label for="modifyPublisher" class="form-label">出版社</label>
                                <input type="text" class="form-control" id="modifyPublisher" name="publisher"
                                       th:value="${book.publisher}">
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="modifyPubYear" class="form-label">出版年份</label>
                                    <input type="number" class="form-control" id="modifyPubYear" name="pubYear"
                                           th:value="${book.pubYear}" min="1800" max="2100">
                                </div>
                                <div class="col-md-6">
                                    <label for="modifyIsbn" class="form-label">ISBN</label>
                                    <input type="text" class="form-control" id="modifyIsbn" name="isbn"
                                          th:value="${book.isbn13 != null ? book.isbn13 : book.isbn10}">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="modifyReason" class="form-label">修改原因</label>
                                <textarea class="form-control" id="modifyReason" name="modifyReason" rows="3" 
                                         placeholder="请简要说明为什么需要修改这些信息" required></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="submit" class="btn btn-primary">提交修改</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 收藏按钮
        const favoriteBtn = document.getElementById('favoriteBtn');
        if (favoriteBtn) {
            favoriteBtn.addEventListener('click', function() {
                const bookId = this.getAttribute('data-book-id');
                const isFavorite = this.getAttribute('data-is-favorite') === 'true';
                
                fetch(`/api/book/${bookId}/${isFavorite ? 'unfavorite' : 'favorite'}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        // 更新按钮状态
                        this.setAttribute('data-is-favorite', !isFavorite);
                        
                        // 更新图标和文本
                        const icon = this.querySelector('i');
                        if (isFavorite) {
                            icon.classList.remove('fas');
                            icon.classList.add('far');
                            this.querySelector('span').textContent = '收藏';
                        } else {
                            icon.classList.remove('far');
                            icon.classList.add('fas');
                            this.querySelector('span').textContent = '已收藏';
                            
                            // 添加动画效果
                            icon.classList.add('animate__animated', 'animate__heartBeat');
                            setTimeout(() => {
                                icon.classList.remove('animate__animated', 'animate__heartBeat');
                            }, 1000);
                        }
                        
                        showToast(isFavorite ? '已移除收藏' : '收藏成功', 'success');
                    } else {
                        showToast('操作失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('操作失败，请重试', 'error');
                });
            });
        }
        
        // 添加到书单
        const addToListButtons = document.querySelectorAll('.add-to-list');
        addToListButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                
                const listId = this.getAttribute('data-list-id');
                const bookId = this.getAttribute('data-book-id');
                
                fetch(`/api/booklist/${listId}/add`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ bookId: bookId })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        showToast('已添加到书单', 'success');
                    } else {
                        showToast(data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('添加失败，请重试', 'error');
                });
            });
        });
        
        // 点赞评论
        const likeButtons = document.querySelectorAll('.like-button');
        likeButtons.forEach(button => {
            button.addEventListener('click', function() {
                const commentId = this.getAttribute('data-comment-id');
                const likeCount = this.querySelector('.like-count');
                const icon = this.querySelector('i');
                
                // 切换点赞状态
                if (this.classList.contains('liked')) {
                    this.classList.remove('liked');
                    icon.classList.remove('fas');
                    icon.classList.add('far');
                    likeCount.textContent = parseInt(likeCount.textContent) - 1;
                } else {
                    this.classList.add('liked');
                    icon.classList.remove('far');
                    icon.classList.add('fas');
                    likeCount.textContent = parseInt(likeCount.textContent) + 1;
                    
                    // 添加点赞动画
                    icon.classList.add('animate__animated', 'animate__heartBeat');
                    setTimeout(() => {
                        icon.classList.remove('animate__animated', 'animate__heartBeat');
                    }, 1000);
                }
                
                // 发送请求到服务器
                fetch(`/api/comment/${commentId}/like`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .catch(error => console.error('Error:', error));
            });
        });
        
        // 回复评论
        const replyLinks = document.querySelectorAll('.reply-link');
        replyLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                
                const commentId = this.getAttribute('data-comment-id');
                const replyForm = document.getElementById(`replyForm-${commentId}`);
                
                // 切换回复表单显示状态
                if (replyForm.style.display === 'none') {
                    // 先隐藏所有回复表单
                    document.querySelectorAll('.reply-form').forEach(form => {
                        form.style.display = 'none';
                    });
                    
                    // 显示当前回复表单
                    replyForm.style.display = 'block';
                    replyForm.querySelector('input[type="text"]').focus();
                } else {
                    replyForm.style.display = 'none';
                }
            });
        });
    });
    </script>
</body>
</html> 